package cn.easyutil.deploy.executor;

import cn.easyutil.deploy.base.SystemType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 执行本地脚本命令
 */
public class LocalCommandExecutor extends AbstractExecutor{

    @Override
    public void exec(List<String> cmds) {
        //重新组装的执行指令
        final String[] execCmds = appandCmds(cmds);
        exec(() -> exec(execCmds,isWaitFor));
    }

    /**
     * 拼接全部指令
     * @param command  指令集合
     * @return
     */
    private String[] appandCmds(List<String> command){
        if (command == null || command.size() == 0) {
            return null;
        }
        List<String> execCommand = new ArrayList<>();
        if(SystemType.current() == SystemType.WINDOWS){
            execCommand.add("cmd");
            execCommand.add("/c");
        }else{
            execCommand.add("/bin/sh");
            execCommand.add("-c");
        }
        StringBuffer sb = new StringBuffer();
        for (String s : command) {
            if(sb.length() != 0){
                sb.append(" && ");
            }
            sb.append(s);
        }
        execCommand.add(sb.toString());
        String[] c = new String[execCommand.size()];
        return execCommand.toArray(c);
    }

    private void exec(String[] all,boolean waitFor) {
        List<String> array = Arrays.asList(all);
        String collect = array.stream().collect(Collectors.joining(","));
        System.out.println("exec:" + collect);
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            process = runtime.exec(all);
            if(waitFor){
                print(process.getInputStream());
                print(process.getErrorStream());
                if(!Thread.currentThread().isInterrupted()){
                    process.waitFor();
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
